/*
 *  Copyright 2019-2020 Zheng Jie
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package com.fzhucc.modules.appletShow.service;

import com.fzhucc.config.FileProperties;
import com.fzhucc.exception.BadRequestException;
import com.fzhucc.modules.appletShow.domain.AppletShow;
import com.fzhucc.modules.appletShow.domain.dto.AppletShowDto;
import com.fzhucc.modules.appletShow.domain.dto.AppletShowQueryCriteria;
import com.fzhucc.modules.appletShow.repository.AppletShowRepository;
import com.fzhucc.modules.appletShow.service.mapstruct.AppletShowMapper;
import com.fzhucc.modules.system.service.UserService;
import com.fzhucc.modules.system.service.dto.UserDto;
import com.fzhucc.utils.*;
import lombok.RequiredArgsConstructor;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.*;

/**
 * @author yyg
 * @website https://eladmin.vip
 * @description 服务实现
 * @date 2022-11-16
 **/
@Service
@RequiredArgsConstructor
public class AppletShowService {

    private final FileProperties properties;

    private final AppletShowRepository appletShowRepository;
    private final AppletShowMapper appletShowMapper;

    private final UserService userService;

    private final String TYPE_SERVICE_PROJECT = "服务项目";

    public Map<String, Object> queryAll(AppletShowQueryCriteria criteria, Pageable pageable) {
        Page<AppletShow> page = appletShowRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria, criteriaBuilder), pageable);
        Page<AppletShowDto> map = page.map(appletShowMapper::toDto);
        List<AppletShowDto> list = map.getContent();
        for (int i = 0; i < list.size(); i++) {
            AppletShowDto appletShowDto = list.get(i);
            if (appletShowDto != null) {
                if (appletShowDto.getCreateUserId() != null) {
                    Long createUserId = appletShowDto.getCreateUserId();
                    UserDto userDto = userService.findById(createUserId);
                    if (userDto != null) {
                        appletShowDto.setCreateUser(userDto);
                    }
                }
            }
        }
        return PageUtil.toPage(map);
    }

    public List<AppletShowDto> queryAll(AppletShowQueryCriteria criteria) {
        return appletShowMapper.toDto(appletShowRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria, criteriaBuilder)));
    }

    public AppletShowDto findById(Integer id) {
        AppletShow appletShow = appletShowRepository.findById(id).orElseGet(AppletShow::new);
        ValidationUtil.isNull(appletShow.getId(), "AppletShow", "id", id);
        return appletShowMapper.toDto(appletShow);
    }

    @Transactional(rollbackFor = Exception.class)
    public AppletShowDto create(AppletShowDto dto) {
        AppletShow resources = appletShowMapper.toEntity(dto);
        Long userId = SecurityUtils.getCurrentUserId();
        if (userId == null) {
            throw new BadRequestException("用户ID未找到");
        }
        if (resources.getType().equals(TYPE_SERVICE_PROJECT)) {
            resources.setIsPush(dto.getIsPush());
            String level = dto.getLevel();
            if (level != null && !level.equals("")) {
                resources.setLevel(Integer.parseInt(dto.getLevel()));
            } else {
                resources.setLevel(null);
            }
        } else {
            resources.setLevel(null);
            resources.setIsPush(0);
        }
        return appletShowMapper.toDto(appletShowRepository.save(resources));
    }

    @Transactional(rollbackFor = Exception.class)
    public void update(AppletShowDto dto) {
        AppletShow resources = appletShowMapper.toEntity(dto);
        Long userId = SecurityUtils.getCurrentUserId();
        if (userId == null) {
            throw new BadRequestException("用户ID未找到");
        }
        dto.setCreateUserId(userId);
        if (resources.getType().equals(TYPE_SERVICE_PROJECT)) {
            resources.setIsPush(dto.getIsPush());
            String level = dto.getLevel();
            if (level != null && !level.equals("")) {
                resources.setLevel(Integer.parseInt(dto.getLevel()));
            } else {
                resources.setLevel(null);
            }
        } else {
            resources.setLevel(null);
            resources.setIsPush(0);
        }
        AppletShow appletShow = appletShowRepository.findById(resources.getId()).orElseGet(AppletShow::new);
        ValidationUtil.isNull(appletShow.getId(), "AppletShow", "id", resources.getId());
        appletShow.copy(resources);
        appletShowRepository.save(appletShow);
    }

    public void deleteAll(Integer[] ids) {
        for (Integer id : ids) {
            appletShowRepository.deleteById(id);
        }
    }

    public void download(List<AppletShowDto> all, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (AppletShowDto appletShow : all) {
            Map<String, Object> map = new LinkedHashMap<>();
            map.put("名称", appletShow.getName());
            map.put("banner图片", appletShow.getImg());
            map.put("简介", appletShow.getIntro());
            map.put("类型", appletShow.getType());
            map.put("领域", appletShow.getField());
            map.put("是否小程序显示", appletShow.getIsShow());
            map.put("显示顺序", appletShow.getSort());
            map.put("创建者user_id", appletShow.getCreateUserId());
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }

    public Map<String, String> douploadpic(MultipartFile multipartFile, Integer id) {
        // 文件大小验证
        FileUtil.checkSize(properties.getAvatarMaxSize(), multipartFile.getSize());
        // 验证文件上传的格式
        String image = "gif jpg png jpeg";
        String fileType = FileUtil.getExtensionName(multipartFile.getOriginalFilename());
        if (fileType != null && !image.contains(fileType)) {
            throw new BadRequestException("文件格式错误！, 仅支持 " + image + " 格式");
        }
        Optional<AppletShow> res = appletShowRepository.findById(id);
        if (res.isPresent()) {
            AppletShow appletShow = res.orElseGet(() -> new AppletShow());
            String oldPath = appletShow.getImg();
            File file = FileUtil.upload(multipartFile, properties.getBanner());
            String path = Objects.requireNonNull(file).getPath();
            String[] files = path.split("file");
            res.get().setImg("/file" + files[1]);
            appletShowRepository.save(res.get());
            if (StringUtils.isNotBlank(oldPath)) {
                FileUtil.del(oldPath);
            }
            return new HashMap<String, String>(1) {{
                put("banner", file.getName());
            }};
        }
        return new HashMap<String, String>(1) {{
            put("banner", "fail");
        }};
    }
}